package com.moyu.crowdsource.service;

import com.aliyun.oss.OSSClient;
import com.moyu.crowdsource.entity.CommodityImage;
import com.moyu.crowdsource.entity.CommodityImageExample;
import com.moyu.crowdsource.mapperdao.CommodityImageMapper;
import com.moyu.crowdsource.util.Msg;
import com.moyu.crowdsource.util.MyUUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

@Service
public class CommodityImageService {

    @Autowired
    CommodityImageMapper commodityImageMapper;

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.access-key-id}")
    private String accessKeyId;

    @Value("${oss.access-key-secret}")
    private String accessKeySecret;

    @Value("${oss.bucket-name}")
    private String bucketName;

    @Value("${oss.firstkey}")
    private String firstkey;

    @Value("${oss.urlhead}")
    private String urlhead;

    public void saveImage(CommodityImage commodityImage){
        commodityImageMapper.insertSelective(commodityImage);
    }

    public void uploadImage(File file, String filename, CommodityImage commodityImage) {

        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上传文件。

        ossClient.putObject(bucketName, firstkey + filename, file);
        // 关闭Client。
        ossClient.shutdown();

        commodityImage.setImageUrl(urlhead + firstkey + filename);
        commodityImage.setImageId(MyUUID.getUUID32());
        saveImage(commodityImage);
    }

    public Msg handleFormUpload(MultipartFile multfile, CommodityImage commodityImage) {
        if (!multfile.isEmpty()) {
            try {
                // 获取文件名
                String fileName = multfile.getOriginalFilename();
                // 获取文件后缀
                String prefix = fileName.substring(fileName.lastIndexOf("."));
                // 用uuid作为文件名，防止生成的临时文件重复
                final File excelFile = File.createTempFile(MyUUID.getUUID32(), prefix);
                // MultipartFile to File
                multfile.transferTo(excelFile);
               uploadImage(excelFile, excelFile.getName(), commodityImage);
                deleteFile(excelFile);
                return Msg.success().add("info", "文件上传成功");
            } catch (Exception e) {
                return Msg.fail().add("转换文件失败", e);
            }
        }
        return Msg.fail().add("info", "文件为空");
    }

    public boolean handleFormUploadBoolean(MultipartFile multfile, CommodityImage commodityImage) {
        if (!multfile.isEmpty()) {
            try {
                // 获取文件名
                String fileName = multfile.getOriginalFilename();
                // 获取文件后缀
                String prefix = fileName.substring(fileName.lastIndexOf("."));
                // 用uuid作为文件名，防止生成的临时文件重复
                final File excelFile = File.createTempFile(MyUUID.getUUID32(), prefix);
                // MultipartFile to File
                multfile.transferTo(excelFile);
                uploadImage(excelFile, excelFile.getName(), commodityImage);
                deleteFile(excelFile);
                return true;
            } catch (Exception e) {
                return false;
            }
        }
        return false;
    }

    public List<CommodityImage> getImageByOrderId(String orderId){
        CommodityImageExample commodityImageExample=new CommodityImageExample();
        CommodityImageExample.Criteria criteria=commodityImageExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        return commodityImageMapper.selectByExample(commodityImageExample);
    }

    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }
}
